from datetime import datetime
import os
import subprocess
import time

from docx import Document
import PyPDF2 as PyPDF2
from flask import request, jsonify, current_app, send_file
from . import admin
from .. import db
from ..models import User, KnowledgeBase


@admin.route("login", methods=['POST'])
def login():
    data = request.get_json()
    username = data['username']
    password = data['password']
    if username == "admin" and password == "123456":
        return jsonify({"success": "登录成功"}), 200
    else:
        return jsonify({"error": "账号或密码错误"}), 400


# 获取用户列表
@admin.route('/users', methods=['GET'])
def get_users():
    users = User.query.all()
    user_list = [{
        'id': user.id,
        'student_id': user.student_id,
        'username': user.username,
        'emergency_contact': user.emergency_contact,
        'created_at': user.created_at,
        'last_login': user.last_login
    } for user in users]

    return jsonify(user_list), 200


# 更新用户信息
@admin.route('/users/<int:user_id>', methods=['PUT'])
def update_user(user_id):
    user = User.query.get_or_404(user_id)
    data = request.get_json()

    if 'username' in data:
        user.username = data['username']
    if 'emergency_contact' in data:
        user.emergency_contact = data['emergency_contact']

    db.session.commit()
    return jsonify({'message': 'User updated successfully.'}), 200


# 删除用户
@admin.route('/users/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
    user = User.query.get_or_404(user_id)
    db.session.delete(user)
    db.session.commit()
    return jsonify({'message': 'User deleted successfully.'}), 200


# 获取所有文章
@admin.route('/getText', methods=['GET'])
def get_articles():
    articles = KnowledgeBase.query.all()
    article_list = [{
        'id': article.id,
        'title': article.title,
        'content': article.content,
        'category': article.category,
        'author': article.author,
        'created_at': article.created_at,
        'updated_at': article.updated_at,
    } for article in articles]

    return jsonify(article_list), 200


# 发布新文章
@admin.route('/addArticles', methods=['POST'])
def add_article():
    data = request.get_json()
    if not data or not all(k in data for k in ('title', 'content', 'category', 'author')):
        return jsonify({'error': 'Missing required fields.'}), 400

    new_article = KnowledgeBase(
        title=data['title'],
        content=data['content'],
        category=data['category'],
        author=data['author']
    )
    db.session.add(new_article)
    db.session.commit()
    return jsonify({'message': '文章发布成功！', 'article_id': new_article.id}), 201


# 删除文章
@admin.route('/deleteText/<int:article_id>', methods=['DELETE'])
def delete_article(article_id):
    article = KnowledgeBase.query.get_or_404(article_id)
    db.session.delete(article)
    db.session.commit()
    return jsonify({'message': '文章删除成功！'}), 200


# 一键上传文章
@admin.route("/autoAddText", methods=['POST'])
def auto_add_text():
    if 'file' not in request.files:
        return jsonify({'error': '没有文件上传'}), 400

    file = request.files['file']

    if file.filename == '':
        return jsonify({'error': '没有选择文件'}), 400

    try:
        title = ""
        category = ""
        author = ""
        body = ""

        if file.filename.endswith('.pdf'):
            # 读取PDF文件
            reader = PyPDF2.PdfReader(file)
            content = []

            for page in reader.pages:
                content.append(page.extract_text())

            content = [text for text in content if text]  # 过滤空内容

            # 提取内容
            for text in content:
                if text.startswith("标题："):
                    title = text[len("标题："):].strip()
                elif text.startswith("类别："):
                    category = text[len("类别："):].strip()
                elif text.startswith("作者："):
                    author = text[len("作者："):].strip()
                elif text.startswith("正文内容："):
                    # 从正文内容开始拼接
                    body = "\n".join(content[content.index(text) + 1:]).strip()
                    break  # 找到正文后跳出循环

        elif file.filename.endswith('.docx'):
            # 读取Word文件
            document = Document(file)
            content = [para.text for para in document.paragraphs if para.text.strip()]
            print(content)
            # 提取内容
            for text in content:
                if text.startswith("标题："):
                    title = text[len("标题："):].strip()
                elif text.startswith("类别："):
                    category = text[len("类别："):].strip()
                elif text.startswith("作者："):
                    author = text[len("作者："):].strip()
                elif text.startswith("正文内容："):
                    # 从正文内容开始拼接
                    body = "\n".join(content[content.index(text) + 1:]).strip()
                    break  # 找到正文后跳出循环

        else:
            return jsonify({'error': '不支持的文件类型，仅支持 .docx 和 .pdf 文件'}), 400

        # 检查是否都成功提取内容
        if not title or not category or not author or not body:
            return jsonify({'error': '文件内容格式不正确，请确保包含标题、类别、作者和正文内容'}), 400

        # 创建知识库条目
        knowledge_entry = KnowledgeBase(title=title, content=body, category=category, author=author)

        # 保存到数据库
        db.session.add(knowledge_entry)
        db.session.commit()

        return jsonify({'message': '文件内容已成功添加到数据库'}), 200

    except Exception as e:
        db.session.rollback()  # 回滚事务
        print(e)
        return jsonify({'error': str(e)}), 500


BACKUP_DIR = 'app/static/backs'


# 查询已有数据库备份
@admin.route("/getDataBackups", methods=["GET"])
def database_all():
    try:
        # 获取备份目录下的所有文件
        backups = [f for f in os.listdir(BACKUP_DIR) if f.endswith('.sql')]
        backup_list = [
            {
                'backup_id': f,
                'backup_date': f.split('_')[1] + ' ' + f.split('_')[2].split('.')[0].replace('-', ':')
            }
            for f in backups if f.startswith('backup_')
        ]
        return jsonify(backup_list), 200
    except Exception as e:
        print(f"Error retrieving backups: {e}")
        return jsonify({'message': 'Error retrieving backups'}), 500


# 一键备份数据库
@admin.route("/createBackup", methods=["POST"])
def database_back():
    try:
        # 备份文件名，使用当前时间命名，格式为 yyyy-mm-dd_hh-mm-ss
        current_time = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
        backup_file = os.path.join(BACKUP_DIR, f'backup_{current_time}.sql')

        # 从配置中获取数据库连接信息
        config = current_app.config['SQLALCHEMY_DATABASE_URI']

        # 解析数据库连接信息
        db_info = config.split('//')[1].split('@')[0].split(':')
        user = db_info[0]
        password = db_info[1]
        database_info = config.split('@')[1]

        # 执行数据库备份的命令，确保替换成你实际的数据库名称
        command = f"mysqldump -u {user} -p{password} {database_info.split('/')[-1]} > {backup_file}"

        # 运行备份命令
        subprocess.run(command, shell=True, check=True)

        return jsonify({'message': 'Backup successful'}), 200
    except Exception as e:
        print(f"Error during backup: {e}")
        return jsonify({'message': 'Backup failed'}), 500


# 恢复数据库
@admin.route("/restoreDataBackup/<backup_id>", methods=["POST"])
def restore_data_backup(backup_id):
    try:
        backup_file = os.path.join(BACKUP_DIR, backup_id)

        if not os.path.exists(backup_file):
            return jsonify({'message': 'Backup file does not exist'}), 404

        # 从配置中获取数据库连接信息
        config = current_app.config['SQLALCHEMY_DATABASE_URI']

        # 解析数据库连接信息
        db_info = config.split('//')[1].split('@')[0].split(':')
        user = db_info[0]
        password = db_info[1]
        database_info = config.split('@')[1]
        command = f"mysql -u {user} -p{password} {database_info.split('/')[-1]} < {backup_file}"

        # 运行恢复命令
        subprocess.run(command, shell=True, check=True)

        return jsonify({'message': 'Restore successful'}), 200
    except subprocess.CalledProcessError as e:
        print(f"Error during restore: {e}")
        return jsonify({'message': 'Restore failed', 'detail': str(e)}), 500
    except Exception as e:
        print(f"General error during restore: {e}")
        return jsonify({'message': 'Restore failed', 'detail': str(e)}), 500


@admin.route("/deleteDataBackup/<backup_id>", methods=["DELETE"])
def delete_data_backup(backup_id):
    backup_file = os.path.join(BACKUP_DIR, backup_id)
    if os.path.exists(backup_file):
        os.remove(backup_file)
        return jsonify({'message': 'Backup deleted successfully'}), 200
    else:
        return jsonify({'message': 'Backup file not found'}), 404
